package com.xinxing.learning.log.desensitization.config;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import com.xinxing.learning.log.desensitization.logback.LcyConsoleAppender;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.Charset;

@Configuration
public class LogbackConfig {

    private static final String CONSOLE_LOG_PATTERN = "%yellow(%date{yyyy-MM-dd HH:mm:ss}) |%highlight(%-5level) |%blue(%thread) |%blue(%file:%line) |%green(%logger) |%cyan(%msg%n)";

    public LogbackConfig() {
        customizeLogbackConfiguration();
    }

    /**
     * 重写LoggerContext
     * 这样可以不用写logback配置文件
     * 关于日志的配置都可以通过编码的方式进行处理
     * 有个问题就是项目启动的时候不能按配置的格式打印日志
     * 这里为了测试设置了两遍在控制台打印日志，实际生产环境可以在这里配置控制台打印和文件打印
     */
    private void customizeLogbackConfiguration() {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        loggerContext.reset();

        LcyConsoleAppender lcyConsoleAppender = new LcyConsoleAppender();
        lcyConsoleAppender.setContext(loggerContext);
        lcyConsoleAppender.setName("console");

        PatternLayoutEncoder encoder = new PatternLayoutEncoder();
        encoder.setContext(loggerContext);
        encoder.setPattern(CONSOLE_LOG_PATTERN);
        encoder.setCharset(Charset.forName("UTF-8"));
        encoder.start();

        lcyConsoleAppender.setEncoder(encoder);
        lcyConsoleAppender.start();
        LcyConsoleAppender lcyConsoleAppender1 = new LcyConsoleAppender();
        lcyConsoleAppender1.setContext(loggerContext);
        lcyConsoleAppender1.setName("console1");

        PatternLayoutEncoder encoder1 = new PatternLayoutEncoder();
        encoder1.setContext(loggerContext);
        encoder1.setPattern(CONSOLE_LOG_PATTERN);
        encoder1.setCharset(Charset.forName("UTF-8"));
        encoder1.start();

        lcyConsoleAppender1.setEncoder(encoder1);
        lcyConsoleAppender1.start();
        Logger rootLogger = loggerContext.getLogger("ROOT");
        rootLogger.setLevel(Level.INFO);
        rootLogger.addAppender(lcyConsoleAppender);
//        rootLogger.addAppender(lcyConsoleAppender1);
        rootLogger.setAdditive(false);
    }
}
